package com.lenin.omena.client;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.MouseUpEvent;
import com.google.gwt.event.dom.client.MouseUpHandler;
import com.google.gwt.maps.client.MapWidget;
import com.google.gwt.maps.client.Maps;
import com.google.gwt.maps.client.control.ControlAnchor;
import com.google.gwt.maps.client.control.ControlPosition;
import com.google.gwt.maps.client.control.LargeMapControl;
import com.google.gwt.maps.client.event.MapClickHandler;
import com.google.gwt.maps.client.event.MapDragHandler;
import com.google.gwt.maps.client.geom.LatLng;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.Widget;
import com.lenin.omena.client.MarkerPanel.State;
import com.lenin.omena.client.event.SaveUserEvent;
import com.lenin.omena.client.event.SaveUserEventHandler;
import com.lenin.omena.shared.AppleMarketServiceAsync;
import com.lenin.omena.shared.SaveUserResult;
import com.lenin.omena.shared.domain.Address;
import com.lenin.omena.shared.domain.Site;
import com.lenin.omena.shared.domain.User;

public class MapPanel extends Composite implements SaveUserEventHandler {

	interface MyUiBinder extends UiBinder<Widget, MapPanel> {
	}

	private static MyUiBinder uiBinder = GWT.create(MyUiBinder.class);

	@UiField
	HTMLPanel mapContainer;

	private MainPanel mainPanel;

	private MapWidget map;

	private CustomMarker activeMarker;
	
	private HashMap<String, LatLng> coordMap;
	
	
	public MapPanel() {

		initWidget(uiBinder.createAndBindUi(this));
		
		SaveUserEvent.register(AppleMarket.getEventBus(), this);
		
		Maps.loadMapsApi(
				"ABQIAAAAdDQXlYkadE6vzIbc5uY9JRSZnzIimKhR1wZlTtv9dSva_dp7ehS3R-1Tjg1C94Ys5PJJouNXECRxrQ",
				"2", false, new Runnable() {
					public void run() {
						buildMapUi();
					}
				});

	}

	
	public void centerMapOnLocation(String location) {
		
		map.setCenter(coordMap.get(location));
		
	}
	
	
	private void buildMapUi() {

		coordMap = new HashMap<String, LatLng>();
		coordMap.put("Oulu", LatLng.newInstance(65.012117, 25.471802));
		coordMap.put("Jyväskylä", LatLng.newInstance(62.245505, 25.745430));
		coordMap.put("Helsinki", LatLng.newInstance(60.17, 24.94));
		coordMap.put("Turku", LatLng.newInstance(60.450339, 22.264996));
		coordMap.put("Tampere", LatLng.newInstance(61.497289, 23.770123));
		
		map = new MapWidget();
		
		map.setScrollWheelZoomEnabled(true);
		map.setContinuousZoom(true);
		
		map.addMapClickHandler(new MapClickHandler() {
			
			public void onClick(MapClickEvent event) {
				
				AppleMarket.hideDialogPopup();
			
			}
			
		});
		
		LatLng startPoint = LatLng.newInstance(60.17, 24.94);
		
		map.setCenter(startPoint);
		
		map.setZoomLevel(12);
		map.setSize("100%", "100%");

		// Add some controls for the zoom level
		LargeMapControl ctrl = new LargeMapControl();
		ControlPosition ctrlPosition = new ControlPosition(ControlAnchor.TOP_LEFT, 20, 25);
		map.addControl(ctrl, ctrlPosition);

		mapContainer.add(map);

		map.checkResizeAndCenter();

		if (mainPanel != null)
			mainPanel.adjustMapContainerHeight();
		
		populateMap();

	}

	public void centerMap() {
		map.checkResizeAndCenter();
	}

	public void setMainPanel(MainPanel mainPanel) {
		this.mainPanel = mainPanel;
	}

	
	public void populateMap() {
		
		AppleMarketServiceAsync service = AppleMarket.getService();

		service.getAllUsers(new AsyncCallback<List<User>>() {

			public void onSuccess(List<User> users) {
				
				for(final User user : users) {
					
					addMarker(user);
					
				}
				
			}

			public void onFailure(Throwable caught) {

			}

		});

	}
	
	
	private void addMarker(final User user) {
		
		if(user.getStatus() == null)
			return;
		
		final Site site = user.getSite();
		final Address address = site.getAddress();
		final LatLng point = LatLng.newInstance(address.getLatitude(), address.getLongitude());
		
		final CustomMarker marker = new CustomMarker(AppleMarket.getMainPanel().getHeaderContainer(), user, point);
		
		
		marker.addClickHandler(new MouseUpHandler() {
			
			public void onMouseUp(MouseUpEvent event) {
				
				if(marker.getState() == State.OPEN) {
					
					marker.toggle();
					activeMarker = null;
						
					AppleMarket.popHelpMessage("MARKER");
					
				} else {
					
					
					if(activeMarker != null) {
						activeMarker.toggle();
						AppleMarket.popHelpMessage("MARKER");
					}
					
					marker.toggle();
					activeMarker = marker;
					
					String msg =
							"Näet nyt ruudulla tuotteita tarjoavan käyttäjän yhteystiedot ja tarjonnan.<br />" +
							"Jos ole kiinnostunut tarjonnasta voit ottaa yhteyttä käyttäjään <b>"+user.getUserInfo().getUserName()+"</b>"+
							"<br/><br/>" +
							"- lähettämällä sähköpostia osoitteeseen: <a href=\"mailto:"+user.getUserInfo().getEmail()+"\">" +
							user.getUserInfo().getEmail()+"</a>";
					
					String phoneNumber = user.getUserInfo().getPhoneNumber();
					if(phoneNumber != null && phoneNumber.length() > 0) {
						msg +=
							"<br />" +
							"- soittamalla puhelinnumeroon "+phoneNumber;
					}
					
					AppleMarket.pushHelpMessage("MARKER", new HTML(msg));
				
				}
				
				
			}
			
		});

		// Add a marker
		map.addOverlay(marker);
		
		
	}
	
	
	@Override
	public void onSaveUser(SaveUserEvent event) {
		
		SaveUserResult result = event.getResult();
		
		if(result.getStatus() == 0) {
			
			User user = result.getUser();
			
			if(user != null) {
				addMarker(user);
			}
			
		}
		
		
	}

}
